package com.swedne.test.threadSafe;


import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MoreTaskTest2 {
    static int num = 0;
    static ExecutorService executorService = Executors.newSingleThreadExecutor();
    private static Vector<String> faceList = new Vector<>();
    private volatile static ArrayList<String> taskList = new ArrayList<>();

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    try {
                        Thread.sleep(2000);
                        synchronized (Object.class) {
                            taskList.add("");
                            Object.class.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        while (true) {
            if (taskList.size() > 0) {
                startTask();
            }
        }
    }

    private static void startTask() {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (MoreTaskTest2.class) {
                        System.out.println("running");
                        Random random = new Random();
                        int i1 = random.nextInt(6000);
                        Thread.sleep(i1);
                        System.out.println("startTask=");
                        notifyTask();
                        MoreTaskTest2.class.wait();
                        System.out.println("endTask====================" + num++);
                        taskList.clear();
                    }
                    synchronized (Object.class) {
                        Object.class.notify();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private static void notifyTask() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (MoreTaskTest2.class) {
                        System.out.println("notify=MoreTaskTest2");
                        Random random = new Random();
//                        int i1 = random.nextInt(10000);
                        Thread.sleep(5000);
                        System.out.println("notify=");
                        MoreTaskTest2.class.notify();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}

